package routines;

import processors.*;
import java.util.*;

public class RoutineCollection {
	private TreeMap<String, List<Routine>> routineCollection;
	
	public RoutineCollection() {
		routineCollection = new TreeMap<String, List<Routine>>();
	}
	
	/**
	 * Inserts a routine in a routine collection, if there isn't already a 
	 * routine with the same name and with the same set of commands in the
	 * collection.
	 * returns 	true if insert was successful
	 * 			false if a routine with the same set of commands an the same 
	 * 				name is already in the collection
	 * routine != null
	 */
	public boolean insertRoutine(Routine routine) {
		List<Routine> l = routineCollection.get(routine.getName());
		if (l == null) {
			routineCollection.put(routine.getName(), 
					l = new ArrayList<Routine>());
		}
		for (Routine each : l) {
			if (each.getUsedCommands().equals(routine.getUsedCommands())) {	
				return false;
			}
		}
		
		l.add(routine);
		
		return true;
	}
	
	/**
	 * Returns the routine with the smallest runtime for a given name and processor
	 * Returns null if the routine does not exist in the routine collection
	 * cpu != null
	 */
	public Routine getBestRoutine(String name, CPU cpu) {
	
		if (routineCollection.get(name) == null) {
			return null;
		}
		Routine smallestRuntime = null;
		for (Routine each : routineCollection.get(name)) {
			if (each.isSupported(cpu) && (smallestRuntime == null || smallestRuntime.getRuntime() < each.getRuntime())) {
				smallestRuntime = each;
			}
		}
		return smallestRuntime;
	}
}
